package cn.bincker.mycaptcha.utils;

import cn.bincker.mycaptcha.basic.exception.InvalidColorException;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.util.StringUtils;

import java.awt.*;

public class ColorUtils {
    /**
     * 解析16进制颜色
     */
    public static Color decodeColor(String hexColor, Color defaultColor){
        if(!StringUtils.hasText(hexColor)) return defaultColor;
        if(!hexColor.startsWith("#")){
            throw new InvalidColorException("错误的颜色值: " + hexColor);
        }
        int value;
        if(hexColor.length() == 4){
            char r = hexColor.charAt(1);
            char g = hexColor.charAt(2);
            char b = hexColor.charAt(3);
            value = Integer.decode(new String(new char[]{'#', r, r, g, g, b, b})) + 0xff000000;
        }else if(hexColor.length() == 5){
            char r = hexColor.charAt(1);
            char g = hexColor.charAt(2);
            char b = hexColor.charAt(3);
            char a = hexColor.charAt(4);
            value = Integer.decode(new String(new char[]{'#', r, r, g, g, b, b})) + (Integer.decode(new String(new char[]{'#', a, a})) << 24);
        }else if(hexColor.length() == 7){
            value = Integer.decode(hexColor) + 0xff000000;
        }else if(hexColor.length() == 9){
            value = Integer.decode(hexColor.substring(0, 7)) + (Integer.parseInt(hexColor.substring(7, 9), 16) << 24);
        }else{
            throw new InvalidColorException("错误的颜色值:" + hexColor);
        }
        return new Color(value, true);
    }

    public static Color decodeColor(String hexColor){
        return decodeColor(hexColor, null);
    }
}
